package com.sw.chinesewriteboard.adapter;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.sw.chinesewriteboard.R;
import com.sw.chinesewriteboard.databinding.ItemZitiBinding;
import com.sw.chinesewriteboard.model.MyTypeface;

import java.util.List;

/**
 * @Description:
 * @author: GordenGao
 * @Email: gordengao124@gmail.com
 * @date: 2021年06月21日 21:27
 */
public class ZitiAdapter extends RecyclerView.Adapter<ZitiAdapter.ZitiViewHolder> {

    private ItemClickListener mListener;
    private List<MyTypeface> mTypefaceList;

    private int curPosition = 0;
    private int prePosition = 0;

    public ZitiAdapter(List<MyTypeface> mTypefaceList, ItemClickListener listener) {
        this.mListener = listener;
        this.mTypefaceList = mTypefaceList;
    }

    @NonNull
    @Override
    public ZitiViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemZitiBinding binding = ItemZitiBinding.inflate(LayoutInflater.from(parent.getContext()));
        return new ZitiViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ZitiViewHolder holder, @SuppressLint("RecyclerView") final int position) {
        final MyTypeface myTypeface = mTypefaceList.get(position);
        holder.btn.setText(myTypeface.getName());
        holder.btn.setTypeface(myTypeface.getTypeface());
        holder.btn.setSelected(position == curPosition);
        if (holder.btn.isSelected()){
            holder.btn.setBackgroundResource(R.mipmap.bg_zt_sel);
            holder.btn.setTextColor(Color.parseColor("#FFFFFF"));
        }else {
            holder.btn.setBackgroundResource(R.mipmap.bg_zt_nor);
            holder.btn.setTextColor(Color.parseColor("#283477"));
        }
        holder.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.onItemClick(myTypeface);
                prePosition = curPosition;
                curPosition = position;
                notifyItemChanged(prePosition);
                notifyItemChanged(curPosition);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mTypefaceList.size();
    }

    public static class ZitiViewHolder extends RecyclerView.ViewHolder {
        Button btn;

        public ZitiViewHolder(@NonNull ItemZitiBinding binding) {
            super(binding.getRoot());
            btn = binding.zitiBtn;
        }
    }

    public interface ItemClickListener {
        void onItemClick(MyTypeface myTypeface);
    }
}
